package org.luxor.commons.workflow.listener;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import org.activiti.engine.delegate.event.ActivitiEntityEvent;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.task.IdentityLink;
import org.luxor.commons.core.utils.StringUtils;
import org.luxor.commons.workflow.component.cache.DeploymentContext;
import org.luxor.commons.workflow.constant.VariableConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 任务执行结束(任务完成后调用)
 *
 * @author Mr.Yan  @date: 2021/10/27
 */
public class TaskCompletedListener implements ActivitiEventHandler {

    private static final Logger log = LoggerFactory.getLogger(TaskCompletedListener.class);

    @Override
    public void handle(ActivitiEvent event) {
        if (event != null && org.springframework.util.StringUtils.hasText(event.getProcessInstanceId())) {
            DeploymentContext.setProcInstId(event.getProcessInstanceId());
        }

        ActivitiEntityEvent entityEvent = (ActivitiEntityEvent) event;
        TaskEntity taskEntity = (TaskEntity) entityEvent.getEntity();

        List<String> candidateUserList = taskEntity.getCandidates().stream().map(IdentityLink::getUserId).filter(StringUtils::isNotBlank).sorted().collect(Collectors.toList());
        List<String> candidateGroupList = taskEntity.getCandidates().stream().map(IdentityLink::getGroupId).filter(StringUtils::isNotBlank).sorted().collect(Collectors.toList());

        String candidate = "userId:" + Arrays.toString(candidateUserList.toArray()) + ",groupId:" + Arrays.toString(candidateGroupList.toArray());
        log.debug("任务结束(TaskCompletedListener). TaskId: " + taskEntity.getId() + "(" + taskEntity.getName()
                + "),ProcInstId: " + entityEvent.getProcessInstanceId()
                + ",ExecutionId: " + taskEntity.getExecutionId()
                + ",Candidate: " + candidate
                + ",Assignee: " + taskEntity.getAssignee());

        // 设置多实例-会签参数
        Object assigneeListValue = taskEntity.getVariable(VariableConst.ASSIGNEE_LIST);
        if (assigneeListValue == null) {
            taskEntity.setVariable(VariableConst.ASSIGNEE_LIST, candidateUserList);
        } else if (assigneeListValue instanceof ArrayNode) {
            List<String> assigneeList = new ArrayList<>();
            for (JsonNode node : (ArrayNode) assigneeListValue) {
                assigneeList.add(node.textValue());
            }
            taskEntity.setVariable(VariableConst.ASSIGNEE_LIST, assigneeList);
        }
    }
}
